package org.jeecg.modules.system.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * create by huweiqiang on 2018/8/9
 */
public class FileUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);


    private static void func(File file) {
        File[] fs = file.listFiles();
        for (File f : fs) {
            if (f.isDirectory())    //若是目录，则递归打印该目录下的文件
                func(f);
            if (f.isFile())        //若是文件，直接打印
                System.out.println(f);
        }
    }


    /**
     * 上传文件到磁盘
     *
     * @param inputStream 文件流
     * @param dirFilePath 磁盘路径
     * @param fileName    文件名称
     * @return
     */
    public static boolean addFileToDisk(InputStream inputStream, String dirFilePath, String fileName) {
        File destFile = FileUtils.createFilePath(dirFilePath);//创建文件目录,若存在则不创建
        String path = String.format("%s/%s", destFile.getAbsoluteFile(), fileName);
        logger.info("==>上传文件路径为:{}", path);
        File f = new File(path);
        inputStreamToFile(inputStream, f);
        return true;
    }

    /**
     * 创建文件目录
     *
     * @param filePath 文件路径
     */
    public static File createFilePath(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            logger.info("==>创建了文件夹：{}", filePath);
            file.mkdirs();
        }
        return file;
    }

    /**
     * 创建文件
     *
     * @param fileName
     * @return
     */
    public static boolean createFile(File fileName) throws Exception {
        try {
            if (!fileName.exists()) {
                fileName.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public static void inputStreamToFile(InputStream inputStream, File file) {
        try (OutputStream outputStream = new FileOutputStream(file)) {
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (FileNotFoundException e) {
            logger.error("==>文件未发现:{}", e);
        } catch (IOException e) {
            logger.error("==>文件IO异常:{}", e);
        }
    }


    /**
     * 保存文件到磁盘
     */
    public static void saveToDisk(MultipartFile file, String dirFilePath, String fileName) {
        InputStream inputStream = null;   //保存文件到磁盘
        try {
            inputStream = file.getInputStream();
            addFileToDisk(inputStream, dirFilePath, fileName);
        } catch (IOException e) {
            logger.error("==>存储北规院规划信息文件失败e:{}", e);
            throw new RuntimeException("==>RuntimeException:存储北规院规划信息文件失败!");
        }
    }

    public void folderMethod2(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        folderMethod2(file2.getAbsolutePath());
                    } else {

                        System.out.println("文件:" + file2.getAbsolutePath());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }

    /**
     * 获取文件扩展名
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 获取文件后缀名字
     *
     * @param filename
     * @return
     */
    public static String getSuffix(String filename) {
        String[] strArray = filename.split("\\.");
        int suffixIndex = strArray.length - 1;
        return strArray[suffixIndex];
    }

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * 获取文件路径
     * filepath 文件完整路径
     */
    public static String getPath(String filePath) {
        int record = filePath.lastIndexOf("\\");
        if(record == -1){
            record = filePath.lastIndexOf("/");
        }
        String path = filePath.substring(0,record );
        return path;
    }


}
